package com.example.demo.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.example.demo.dao.IShortLinkDao;
import com.example.demo.model.ShortLink;
import com.example.demo.service.IShortLinkService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author chxbca
 */
@Service
@RequiredArgsConstructor
public class ShortLinkServiceImpl implements IShortLinkService {

    private final IShortLinkDao shortLinkDao;

    @Override
    public String convertShortLink(String longLink) {
        Optional<ShortLink> shortLinkOptional = shortLinkDao.findByLongLink(longLink);
        ShortLink shortLink = shortLinkOptional.orElseGet(() -> generateShortLink(longLink));
        return shortLink.getShortLink();
    }

    @Override
    public String convertLongLink(String shortLink) {
        return shortLinkDao.findByShortLink(shortLink).
                orElseThrow(() -> new RuntimeException("短链接不存在")).getLongLink();
    }

    private ShortLink generateShortLink(String longLink) {
        String shortLinkCode = calculateNoConflictShortLink(longLink);
        ShortLink shortLink = ShortLink.builder().longLink(longLink).shortLink(shortLinkCode).build();
        return shortLinkDao.save(shortLink);
    }

    private String calculateNoConflictShortLink(String longLink) {
        final MD5 md5 = MD5.create();
        String shortLinkCode = md5.digestHex(longLink).substring(0, 8);
        while (shortLinkDao.existsByShortLink(shortLinkCode)) {
            shortLinkCode = md5.digestHex(shortLinkCode).substring(0, 8);
        }
        return shortLinkCode;
    }
}
